package test.design.chain.dubbo;

import java.util.ArrayList;
import java.util.List;

import test.design.chain.Request;
import test.design.chain.Response;

public class Chain {
	
	List<Filter> filters = new ArrayList<>();
	
	public Chain addFilter(Filter filter) {
		filters.add(filter);
		return this;
	}
	
	public void doFilter(Invoker last, Request request, Response response) {
		for(int i = filters.size() - 1;i >= 0;i--) {
			Filter filter = filters.get(i);
			Invoker next = last;
			last = new Invoker() {
				
				@Override
				public void invoke(Request request, Response response) {
					filter.doFilter(next, request, response);
				}
			};
		}
		
		last.invoke(request, response);
	}

	public static void main(String[] args) {
		Chain chain = new Chain();
		chain.addFilter(new LogFilter()).addFilter(new CheckFilter());
		
		Request request = new Request();
		Response response = new Response();
		response.out = "";
		
		chain.doFilter(new Invoker() {
			
			@Override
			public void invoke(Request request, Response response) {
				new UserService().hello(request, response);
			}
		}, request, response);
		
		
		/**invoke(req, res) {
		 * 		filter.doFilter(invoker, req, res)
		 * }
		 * 
		 * 
		 */
	}
	
}
